#pragma once
#include<iostream>
#include<string>
#include<vector>
#include"InetAddr.hpp"

class Route
{
private:
    bool IsExists(const InetAddr &addr)
    {
        for (auto &user : _online_user)
        {
            if (user == addr)
            {
                return true;
            }
        }
        return false;
    }
    void AddUser(const InetAddr&addr)
    {
        if(!IsExists(addr))
            _online_user.push_back(addr);
    }
    void DeleteUser(std::string &message,InetAddr&addr)
    {
        if(message == "QUIT")
        {
            auto iter = _online_user.begin();
            for(; iter != _online_user.end(); iter++)
            {
                if(*iter == addr)
                {
                    _online_user.erase(iter);
                    break;
                }
            }
        }
    }
    void SendMessageToAll(int sockfd,std::string &message,InetAddr &addr)
    {
        for(auto&user:_online_user)
        {
            LOG(Loglevel::DEBUG) << "route [" << message << "] to : " << user.ToString();
            
            std::string info=addr.ToString();
            info +="# ";
            info +=message;
            
            sendto(sockfd,info.c_str(),info.size(),0,addr.Addr(),addr.Length());
        }
    }
public:
    Route()
    {}
    void RouteToMessage(int sockfd,std::string &message,InetAddr &addr)
    {
        // LOG(Loglevel::DEBUG)<<"到这了吗";
        AddUser(addr);

        SendMessageToAll(sockfd,message,addr);

        DeleteUser(message,addr);
    }
    ~Route()
    {}
private:
    std::vector<InetAddr> _online_user;
};